//
//  EditVCExtension.swift
//  ShiZhe
//
//  Created by 陈卿伟 on 16/10/12.
//  Copyright © 2016年 陈卿伟. All rights reserved.
//

import UIKit

//MARK:--对文字的操作  在这里
extension EditViewController{
    //对后面输入的文字加粗 或者取消加粗
    func boldForNextText(selecte:Bool){
        if selecte == true{
            self.bodyView.inputBodyTV.typingAttributes[NSFontAttributeName] = BaseFunc.getLightFont(15)
        }else{
            self.bodyView.inputBodyTV.typingAttributes[NSFontAttributeName] = UIFont.boldSystemFontOfSize(14.7*SCALEW)
        }
    }
    
    //对选中的文字加粗 或者 取消加粗
    func boldForSelecteText(selecteRange:NSRange){
        let string = NSMutableAttributedString(attributedString: bodyView.inputBodyTV.attributedText)
        let selecteString = NSMutableAttributedString(attributedString: bodyView.inputBodyTV.attributedText.attributedSubstringFromRange(selecteRange))
        selecteString.enumerateAttribute(NSFontAttributeName, inRange: NSMakeRange(0, selecteString.length), options: .Reverse) { (obj, _, _) in
            let result = (obj! as! UIFont).fontName
            if result == "PingFangSC-Light" || result == "STHeitiSC-Light"{
                string.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(14.7*SCALEW), range: selecteRange)
            }else{
                string.addAttribute(NSFontAttributeName, value: BaseFunc.getLightFont(15), range: selecteRange)
            }
            
            let newSelecteRange = NSMakeRange(selecteRange.location+selecteRange.length, 0)
            self.bodyView.inputBodyTV.attributedText = string
            //恢复光标的位置（上面一句代码执行之后，光标会移到最后面）
            self.bodyView.inputBodyTV.selectedRange = newSelecteRange
        }
    }
    
    //对后续文字加删除线
    func addStrikethroughForNextText(selecte:Bool){
        if selecte == true{
            self.bodyView.inputBodyTV.typingAttributes[NSStrikethroughStyleAttributeName] =  (NSUnderlineStyle.StyleNone.hashValue )
        }else{
            self.bodyView.inputBodyTV.typingAttributes[NSStrikethroughStyleAttributeName] =  (NSUnderlineStyle.StyleSingle.hashValue )
        }
    }
    
    //对选中的文字加删除线
    func addStrikethroughForSelecteText(selecteRange:NSRange){
        let string = NSMutableAttributedString(attributedString: bodyView.inputBodyTV.attributedText)
        let selecteString = NSMutableAttributedString(attributedString: bodyView.inputBodyTV.attributedText.attributedSubstringFromRange(selecteRange))
        selecteString.enumerateAttribute(NSStrikethroughStyleAttributeName, inRange: NSMakeRange(0, selecteString.length), options: .Reverse) { (obj, _, _) in
            if obj != nil{
                string.addAttribute(NSStrikethroughStyleAttributeName, value: NSUnderlineStyle.StyleNone.hashValue, range: selecteRange)
            }else{
                string.addAttribute(NSStrikethroughStyleAttributeName, value: NSUnderlineStyle.StyleSingle.hashValue, range: selecteRange)
            }
            let newSelecteRange = NSMakeRange(selecteRange.location+selecteRange.length, 0)
            self.bodyView.inputBodyTV.attributedText = string
            //恢复光标的位置（上面一句代码执行之后，光标会移到最后面）
            self.bodyView.inputBodyTV.selectedRange = newSelecteRange
        }
    }
    
    //对后续文字加斜体
    func addObliquenessForNextText(selecte:Bool){
        if selecte == false{
            bodyView.inputBodyTV.typingAttributes[NSObliquenessAttributeName] = 0.5
        }else{
            bodyView.inputBodyTV.typingAttributes[NSObliquenessAttributeName] = 0
        }
    }
    
    //对选中文字加斜体
    func addObliquenessForSelecteText(selecteRange:NSRange){
        let string = NSMutableAttributedString(attributedString: bodyView.inputBodyTV.attributedText)
        let selecteString = NSMutableAttributedString(attributedString: bodyView.inputBodyTV.attributedText.attributedSubstringFromRange(selecteRange))
        selecteString.enumerateAttribute(NSObliquenessAttributeName, inRange: NSMakeRange(0, selecteString.length), options: .Reverse) { (obj, _, _) in
            if (obj) != nil{
                string.addAttribute(NSObliquenessAttributeName, value: 0, range: selecteRange)
            }else{
                string.addAttribute(NSObliquenessAttributeName, value: 0.5, range: selecteRange)
            }
            //记住现在光标应该所在的位置
            let newSelecteRange = NSMakeRange(selecteRange.location+selecteRange.length, 0)
            self.bodyView.inputBodyTV.attributedText = string
            //恢复光标的位置（上面一句代码执行之后，光标会移到最后面）
            self.bodyView.inputBodyTV.selectedRange = newSelecteRange
        }
    }
    
    
    //对后面的字体添加设置标题大小
    func setupTitleHForNextText(selecte:Bool,fontSize:CGFloat){
        if selecte == true{
            self.bodyView.inputBodyTV.typingAttributes[NSFontAttributeName] = BaseFunc.getLightFont(15)
        }else{
            self.bodyView.inputBodyTV.typingAttributes[NSFontAttributeName] = UIFont(name: "Verdana-Bold", size: fontSize*SCALEW)
        }
    }
}

//MARK:--插入的操作 在这里
extension EditViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    //使用相机点击事件
    func setCameraButtonClick(){
        if UIImagePickerController.isSourceTypeAvailable(.Camera){
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.sourceType = UIImagePickerControllerSourceType.Camera
            self.presentViewController(picker, animated: true, completion: { () -> Void in
            })
        }else{
            showHUD.showTopHud(self.view, text: "调用相机出错")
        }
    }
    
    //使用相册点击事件
    func setAlbumButtonClick(){
        if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            self.presentViewController(picker, animated: true, completion: {
                () -> Void in
            })
        }else{
            showHUD.showTopHud(self.view, text: "读取相册错误")
        }
    }
    
    //选择图片成功后代理
    func imagePickerController(picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        //获取选择的原图
        var imageX:UIImage!
        if(picker.allowsEditing){
            //裁剪后图片
            imageX = info[UIImagePickerControllerEditedImage] as! UIImage
        }else{
            //原始图片
            imageX = info[UIImagePickerControllerOriginalImage] as! UIImage
        }
        //图片控制器退出
        picker.dismissViewControllerAnimated(true, completion: {
            () -> Void in
            self.insertImageToTextView(imageX)
        })
    }
    
    //拍照的navigationBar是独立的，需要在这里独立设置
    func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
        navigationController.navigationBar.tintColor = UIColor.whiteColor()
        navigationController.navigationBar.barTintColor = UIColor.blackColor()
    }
    
    //选择图片成功之后将图片插入textview
    func insertImageToTextView(image:UIImage){
        let string = NSMutableAttributedString(attributedString: bodyView.inputBodyTV.attributedText)
        let selecteRange = bodyView.inputBodyTV.selectedRange
        let textAttachment = NSTextAttachment(data: nil, ofType: nil)
        textAttachment.image = image
        let imageWidth = bodyView.inputBodyTV.frame.width - 10
        let imageHeight = image.size.height/image.size.width*imageWidth
        textAttachment.bounds = CGRectMake(0, 0, imageWidth, imageHeight)
        let textAttachmentString = NSAttributedString(attachment: textAttachment)
        string.insertAttributedString(textAttachmentString, atIndex: selecteRange.location)
        let newSelecteRange = NSMakeRange(selecteRange.location+1, 0)
        self.bodyView.inputBodyTV.attributedText = string
        //插入图片之后，字体就会改变，textview从新赋值完毕之后掉用，将后面输入的字体改回原来的
        self.bodyView.inputBodyTV.typingAttributes[NSFontAttributeName] = BaseFunc.getLightFont(15)
        //恢复光标的位置（上面一句代码执行之后，光标会移到最后面）
        self.whentextbodyEditing()
        self.bodyView.inputBodyTV.becomeFirstResponder()
        self.bodyView.inputBodyTV.selectedRange = newSelecteRange
    }
    
    //插入链接
    func insertLinking(){
        alertControll = UIAlertController(title: "插入超链接", message: "", preferredStyle: .Alert)
        alertControll.addTextFieldWithConfigurationHandler { (textF) in
            textF.placeholder = "输入链接地址"
            textF.keyboardType = .URL
            textF.text = "http://"
        }
        alertControll.addTextFieldWithConfigurationHandler { (textF) in
            textF.placeholder = "输入链接标题"
        }
        let textF1 = alertControll.textFields![0]//输入链接
        let textF2 = alertControll.textFields![1]//输入标题
        textF1.delegate = self
        textF2.delegate = self
        let actionCancel = UIAlertAction(title: "取消", style: .Cancel, handler: nil)
        let actionOk = UIAlertAction(title: "确定", style: .Default) { (action) in
            let insertString = NSMutableAttributedString(string: "\(textF2.text!)")
            let string = NSMutableAttributedString(attributedString: self.bodyView.inputBodyTV.attributedText)
            insertString.addAttribute(NSLinkAttributeName, value: NSURL(string: textF1.text!)!, range: NSMakeRange(0, insertString.length))
            insertString.addAttribute(NSFontAttributeName, value: BaseFunc.getLightFont(15), range: NSMakeRange(0, insertString.length))
            let index = self.bodyView.inputBodyTV.selectedRange.location
            string.insertAttributedString(insertString, atIndex: index)
            self.bodyView.inputBodyTV.attributedText = string
            self.bodyView.inputBodyTV.selectedRange = NSMakeRange(index+insertString.length, 0)
            let string2 = NSMutableAttributedString(attributedString: self.bodyView.inputBodyTV.attributedText)
            string2.removeAttribute(NSLinkAttributeName, range: NSMakeRange(string2.length, 0))
            self.bodyView.inputBodyTV.attributedText = string2
        }
        actionOk.enabled = false
        alertControll.addAction(actionCancel)
        alertControll.addAction(actionOk)
        self.presentViewController(alertControll, animated: true, completion: nil)
    }
    
    
    //插入分割线
    func insertSplitLine(){
        let bodyString = self.bodyView.inputBodyTV.attributedText
        let string = NSMutableAttributedString(attributedString: bodyString)
        let textattament = NSTextAttachment(data: nil, ofType: nil)
        textattament.image = UIImage(named: "splitLine")
        textattament.bounds = CGRectMake(0, 0, WidthAPP-30*SCALEW, 40)
        let insertString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: textattament))
        insertString.addAttribute(NSFontAttributeName, value: BaseFunc.getLightFont(15), range: NSMakeRange(0, insertString.length))
        let selecteRange = self.bodyView.inputBodyTV.selectedRange
        string.insertAttributedString(insertString, atIndex:selecteRange.location)
        self.bodyView.inputBodyTV.attributedText = string
        self.bodyView.inputBodyTV.selectedRange = NSMakeRange(selecteRange.location+insertString.length, 0)
    }
    
    //string转html
    func takeStringToHtml(){
        let string = self.bodyView.inputBodyTV.attributedText
        let document = [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType]
        do{
            let htmlData = try string.dataFromRange(NSMakeRange(0, string.length), documentAttributes: document)
            let htmlString = String(data: htmlData, encoding: NSUTF8StringEncoding)
            let attributeString = NSAttributedString(string: htmlString!)
            print(attributeString)
            self.bodyView.inputBodyTV.attributedText = attributeString
        }catch{
            print("转换失败")
        }
    }
}

//判断插入超链接的确定按钮是否可用
extension EditViewController:UITextFieldDelegate{
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let textf1 = alertControll.textFields![0]
        let textf2 = alertControll.textFields![1]
        if textf1.text?.isEmpty == false && textf2.text?.isEmpty == false{
            alertControll.actions[1].enabled = true
        }
        return true
    }
}

//MARK:--插入代码
extension EditViewController{
    func insertCode(){
        let bodyTextView = self.bodyView.inputBodyTV
        let spaceString = NSAttributedString(string: "\r")
        
        let selectedRange = bodyTextView.selectedRange
        let textattament = NSTextAttachment(data: nil, ofType: nil)
        textattament.image = UIImage(named: "codeBoard")
        textattament.bounds = CGRectMake(0, 0, WidthAPP-30*SCALEW, 50)
        let insertString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: textattament))
        let pragraStyle = NSMutableParagraphStyle()
        pragraStyle.paragraphSpacing = 20
        insertString.addAttribute(NSParagraphStyleAttributeName, value: pragraStyle, range: NSMakeRange(0, insertString.length))
        insertString.addAttribute(NSFontAttributeName, value: BaseFunc.getLightFont(15), range: NSMakeRange(0, insertString.length))
        let string = NSMutableAttributedString(attributedString: bodyTextView.attributedText)
        string.insertAttributedString(spaceString, atIndex: selectedRange.location)
        bodyTextView.attributedText = string
        let scrollTextRange = bodyTextView.selectedTextRange!
        let insertRange = bodyTextView.selectedRange
        self.attachmentRangeArr.insert(insertRange.location, atIndex: scrollNum)
        addScrollViewInCodeTextAttament(scrollTextRange)
        string.insertAttributedString(insertString, atIndex: selectedRange.location+spaceString.length)
        bodyTextView.attributedText = string
        
    }
    
    //在代码的框上面添加scrollView
    func addScrollViewInCodeTextAttament(range:UITextRange){
        //得到创建了代码编辑框的位置
        let scrollRect = self.bodyView.inputBodyTV.caretRectForPosition(range.start)
        let scrollView = UIScrollView(frame: CGRectMake(10*SCALEW,scrollRect.origin.y+10,WidthAPP-40*SCALEW,30))
        scrollView.tag = 6790+scrollNum
        self.bodyView.inputBodyTV.addSubview(scrollView)
        
        //在这个scrollview上创建一个textview
        let textView = UITextView(frame: scrollView.bounds)
        textView.tag = 9160+scrollNum
        textView.delegate = self
        textView.scrollEnabled = false
        textView.backgroundColor = UIColor.clearColor()
        textView.font = UIFont.italicSystemFontOfSize(13)
        textView.textColor = UIColor.blackColor()
        textView.textAlignment = .Left
        textView.keyboardType = .Default
        scrollView.addSubview(textView)
        textView.becomeFirstResponder()
        
        scrollNum += 1//创建完一次代码编辑器scrollnum加一
    }
}


//MARK:--通知
extension EditViewController{
//    func attachmentBoundsForTextContainer(textContainer: NSTextContainer?, proposedLineFragment lineFrag: CGRect, glyphPosition position: CGPoint, characterIndex charIndex: Int) -> CGRect {
//        <#code#>
//    }
//    
//    func imageForBounds(imageBounds: CGRect, textContainer: NSTextContainer?, characterIndex charIndex: Int) -> UIImage? {
//        <#code#>
//    }
}





















